package com.pestano.aula2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.opengl.Visibility;
import android.os.Bundle;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ClienteActivity extends Activity {
	/** Called when the activity is first created. */

	private SQLiteDatabase db;
	
	private ListView listaView;
	
	private EditText nome;
	
	private EditText email;
	
	private Button btSalvar;
	
	private String idClienteSelecionado;
	
	private Button btRemover;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sqlite);
	    db = openOrCreateDatabase("dados.db",
				Context.MODE_PRIVATE, null);// cria banco ou abre se ja existe
		db.execSQL("CREATE TABLE IF NOT EXISTS clientes (id INTEGER PRIMARY KEY AUTOINCREMENT, nome varchar(50), email varchar(50))");
		listaView = (ListView) findViewById(R.id.listView1);
	    nome = (EditText) findViewById(R.id.editText1);
	    email = (EditText) findViewById(R.id.editText2);
	    btSalvar = (Button) findViewById(R.id.button1);
	    btRemover = (Button) findViewById(R.id.bt_remover);
		carregaListaClientes();
		
	}
	
	private void criaListView() {
		listaView = (ListView) findViewById(R.id.listView1);
		List<Map<String,String>> listaCliente = new ArrayList<Map<String,String>>(); 
		String[] from = {"id","nome","email"};
		
		int[] to = {R.id.textView1,R.id.textView2,R.id.textView3}; 
		SimpleAdapter sa = new SimpleAdapter(getBaseContext(), listaCliente, R.layout.listar, from, to);
		listaView.setAdapter(sa);
		
	}

	@SuppressWarnings("unchecked")
	private void carregaListaClientes(){
		List<Map<String,String>> listaCliente = new ArrayList<Map<String,String>>(); 
		String[] from = {"nome","email"};
		
		String[] args = {};
		Cursor c = db.rawQuery("SELECT * FROM clientes", args);
		while(c.moveToNext()){
			Map<String, String> m = new HashMap<String, String>();
			m.put("id", c.getInt(0)+"");
			m.put("nome", c.getString(1));
			m.put("email", c.getString(2)); 
			listaCliente.add(m);
		}
		c.close();
		db.close();
		int[] to = {R.id.textView2,R.id.textView1}; 
		SimpleAdapter sa = new SimpleAdapter(getBaseContext(), listaCliente, R.layout.listar, from, to);
		listaView.setAdapter(sa);
		listaView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				 
				Map<String,String> cliente = (Map<String, String>) arg0.getAdapter().getItem(arg2);
			    nome.setText(cliente.get("nome"));
			    email.setText(cliente.get("email"));
			    btRemover.setVisibility(Button.VISIBLE);
			    idClienteSelecionado = cliente.get("id");
			}
		});
		
	}
	
	private void carregaListaClientes(List<Map<String,String>> listaCliente){
		String[] from = {"nome","email"};
		int[] to = {R.id.textView2,R.id.textView1}; 
		SimpleAdapter sa = new SimpleAdapter(getBaseContext(), listaCliente, R.layout.listar, from, to);
		listaView.setAdapter(sa);
		listaView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				 
				Map<String,String> cliente = (Map<String, String>) arg0.getAdapter().getItem(arg2);
			    nome.setText(cliente.get("nome"));
			    email.setText(cliente.get("email"));
			    btRemover.setVisibility(Button.VISIBLE);
			    idClienteSelecionado = cliente.get("id");
			}
		});
	}
	
	

	public void salvarClick(View v) {
		try {
			
			if(!ValidacaoUtil.isPreenchido(nome, "Informe o nome.")){
				return;
			}
			if(!ValidacaoUtil.isPreenchido(nome, "Informe o email.")){
				return;
			}
			ContentValues values = new ContentValues();
			values.put("nome", nome.getText().toString());
			values.put("email", email.getText().toString());
			db = openOrCreateDatabase("dados.db",
					Context.MODE_PRIVATE, null);
			db.insert("clientes", "id", values);
			Toast.makeText(getBaseContext(), "Cliente insirido com sucesso,", Toast.LENGTH_LONG).show();
			nome.setText("");
			email.setText("");
			carregaListaClientes();
			//db.close();
		} catch (Exception e) {
			Builder b = new Builder(getBaseContext());
			b.setPositiveButton("Ok", null);
			b.setMessage("Ocorreu um erro inesperado ao inserir registro.");
			b.show();
		}
	}
	
	public void removerClick(View v) {
		try {
			
			ContentValues values = new ContentValues();
			values.put("nome", nome.getText().toString());
			values.put("email", email.getText().toString());
			db = openOrCreateDatabase("dados.db",
					Context.MODE_PRIVATE, null);
			
			String[] args = {idClienteSelecionado};
			db.delete("clientes","id=?" , args);
			Toast.makeText(getBaseContext(), "Cliente removido com sucesso,", Toast.LENGTH_LONG).show();
			nome.setText("");
			email.setText("");
			btRemover.setVisibility(Button.INVISIBLE);
			carregaListaClientes();
			//db.close();
		} catch (Exception e) {
			Builder b = new Builder(getBaseContext());
			b.setPositiveButton("Ok", null);
			b.setMessage("Ocorreu um erro inesperado ao inserir registro.");
			b.show();
		}
	}

	public void filtrarClick(View v){
		
		if(!ValidacaoUtil.isPreenchido(email) && !ValidacaoUtil.isPreenchido(nome)){
			Toast.makeText(getBaseContext(),"Informe ao menos um criterio de pesquisa", Toast.LENGTH_LONG).show();
		}
		StringBuilder selection = new StringBuilder();
		List<String> args = new ArrayList<String>();
		if(ValidacaoUtil.isPreenchido(nome)){
			 selection.append("nome=?");
			 args.add(nome.getText().toString());
		}
		if(ValidacaoUtil.isPreenchido(email)){
			if(selection.length() > 0){
				selection.append(" and ");
			}
			selection.append("email=?");
			args.add(email.getText().toString());
		}
		String[] cols = {"nome","email"};
		String[] argsArray = args.toArray(new String[]{});
		List<Map<String,String>> listaCliente = new ArrayList<Map<String,String>>();
		db = openOrCreateDatabase("dados.db",
				Context.MODE_PRIVATE, null);
		Cursor c = db.query("clientes",cols , selection.toString(),argsArray, null, null, null);
		while(c.moveToNext()){
			Map<String, String> m = new HashMap<String, String>();
			m.put("nome", c.getString(0));
			m.put("email", c.getString(1)); 
			listaCliente.add(m);
		}
		this.carregaListaClientes(listaCliente);
		db.close();
		c.close();
	}

}